package com.itboye.mengwu.app.ui.aiwujia;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.BasePtr;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.adapter.YuErJingAdapter;
import com.itboye.mengwu.app.login.ui.LoginActivity;
import com.itboye.mengwu.app.ui.aizhiwu.GeRenActivity;
import com.itboye.mengwu.data.model.BiaoQianModel;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.model.TieZiBaoHanReply;
import com.itboye.mengwu.data.model.TieZiBaoHanReply.GetAList;
import com.itboye.mengwu.data.presenter.BiaoQianPresenter;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.ui.shop.FlowLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * 2016.5.04
 */
public class FragmentYuEr extends BaseFragment implements Observer {

    private ListView listview;
    TextView mama_share;
    TextView mama_quest;
    TextView care;
    TextView question;
    TextView question_show;
    List<ImageView> imageViews;
    View headermamafenxiang;
    TextView hot_talk;
    TieZiPresenter presenter;
    private YuErJingAdapter adapter;
    ArrayList<TieZiBaoHanReply.GetAList> aLists = new ArrayList<TieZiBaoHanReply.GetAList>();
    TextView biaoqian_show;
    TextView baby_years;
    TextView baby_sex;
    boolean click;
    BiaoQianPresenter biaoqianPresenter;
    ArrayList<BiaoQianModel> biaoqianlist = new ArrayList<BiaoQianModel>();
    FlowLayout flowLayout;
    // FlowLayout flowLayout2;
    FlowLayout content_flowlayout;
    int pageNo = 1;
    int count = 0;
    StringBuilder builder = new StringBuilder();
    TextView tv;
    LuntanTieZiBean model = new LuntanTieZiBean();
    String authorID;
    String fid = "7";
    String type = "load";
    boolean tag = true;
    String zuixin = "1";
    int di;
    // ImageView tiwen, fenxiang;
    TextView tiwen_tv;
    PtrFrameLayout ptr;

    @Override
    public int initView() {
        return R.layout.yuerjing_layout;
    }

    @Override
    public void onMyActivityCreated() {
        showProgressDialog("数据加载中，请稍后", true);
        presenter = new TieZiPresenter(this);
        biaoqianPresenter = new BiaoQianPresenter(this);
        biaoqianPresenter.QueryBiaoQian(
                SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "",
                "2", "10");
        headermamafenxiang = LayoutInflater.from(getActivity()).inflate(
                R.layout.headeriew_mamafenxiang, null);
        flowLayout = (FlowLayout) headermamafenxiang
                .findViewById(R.id.flowLayout);
        tiwen_tv = (TextView) headermamafenxiang.findViewById(R.id.tiwen_tv);
        listview.addHeaderView(headermamafenxiang);
        adapter = new YuErJingAdapter(getActivity(), ImgOnClickListener,
                headclick, aLists, "0", deleteclick);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                    Intent intent2 = new Intent(getActivity(),
                            YuErJingMomDetailActivity.class);
                Log.d("ararara",arg2+"\t"+aLists.size());
                    intent2.putExtra("tid", aLists.get(arg2-1).getTid());
                    intent2.putExtra("title", aLists.get(arg2-1).getSubject());
                    startActivity(intent2);

            }
        });
        BasePtr.setPagedPtrStyle(ptr);
        ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                pageNo++;
                model.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
                        + "");
                model.setFid(fid);
                model.setPage_no(pageNo + "");
                model.setMaxReply("2");
                model.setFresh(zuixin);
                presenter.getInfo(model);
                tag = false;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                model.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
                        + "");
                model.setFid(fid);
                model.setPage_no(pageNo + "");
                model.setMaxReply("2");
                model.setFresh(zuixin);
                presenter.getInfo(model);
                tag = false;
            }
        });

    }

    OnClickListener headclick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getActivity(), GeRenActivity.class);
            intent.putExtra("uid",
                    SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
                            + "");
            intent.putExtra("fromUid", v.getTag() + "");
            startActivity(intent);
        }

    };

    OnClickListener deleteclick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            // Intent intent = new Intent(getActivity(), GeRenActivity.class);
            // intent.putExtra("uid", uid);
            // intent.putExtra("fromUid", v.getTag() + "");
            // startActivity(intent);
        }

    };
    protected String tid;

    public void onResume() {
        super.onResume();
        model.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
                + "");
        model.setFid(fid);
        model.setPage_no(pageNo + "");
        model.setMaxReply("2");
        model.setFresh(zuixin);
        presenter.getInfo(model);
    }

    OnClickListener ImgOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            tid = (String) v.getTag(R.id.tag_first);
            String isFav = (String) v.getTag(R.id.tag_second);
            di = (int) v.getTag(R.id.imgCollectionNum);
            if (judgeLogin()) {
                if ("0".equals(isFav)) {
                    showProgressDialog("请求提交中，请稍后", true);
                    presenter.dianzan(
                            SPUtils.get(getActivity(), null,
                                    SpPublicParams.UID, "") + "", "1", tid);
                    adapter.notifyDataSetChanged();

                } else {
                    ByAlert.alert("已经点过赞了");

                }
            }

        }
    };

    public boolean judgeLogin() {
        if (SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "" == null
                || (SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "")
                .equals("")) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            return false;
        } else {
            return true;
        }
    }

    @Override
    protected void smartInject(View view) {
        // TODO Auto-generated method stub

        super.smartInject(view);
        mama_quest = (TextView) view.findViewById(R.id.mama_quest);
        mama_share = (TextView) view.findViewById(R.id.mama_share);
        // mama_share.setTextColor(getResources().getColor(R.color.main_color));
        // mama_quest.setTextColor(getResources().getColor(R.color.black));
        mama_quest.setOnClickListener(new OnClickListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("ResourceAsColor")
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (tag) {
                    tiwen_tv.setText("妈妈提问");
                    showProgressDialog("妈妈提问加载中，请稍后", true);
                    mama_quest.setText("・妈妈提问・");
                    mama_share.setText("妈妈分享");
                    mama_quest.setTextColor(getResources().getColor(
                            R.color.main_color));
                    mama_share.setTextColor(getResources().getColor(
                            R.color.black_view));
                    type = "clean";
                    fid = "8";
                    model.setFid(fid);
                    model.setFresh(zuixin);
                    model.setPage_no("1");
                    presenter.getInfo(model);
                    // listview.addHeaderView(headermamatiwen);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        mama_share.setOnClickListener(new OnClickListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                // listview.removeHeaderView(headermamatiwen);
                if (tag) {
                    tiwen_tv.setText("妈妈分享");
                    showProgressDialog("妈妈分享加载中，请稍后", true);
                    mama_share.setTextColor(getResources().getColor(
                            R.color.main_color));
                    mama_quest.setText("妈妈提问");
                    mama_share.setText("・妈妈分享・");
                    mama_quest.setTextColor(getResources().getColor(
                            R.color.black_view));
                    type = "clean";
                    fid = "7";
                    model.setFid(fid);
                    model.setPage_no("1");
                    model.setFresh(zuixin);
                    presenter.getInfo(model);
                    // listview.addHeaderView(headermamafenxiang);
                    adapter.notifyDataSetChanged();
                }
            }
        });

    }

    @SuppressWarnings("deprecation")
    private void setbiaoqianname() {
        for (int i = 0; i < biaoqianlist.size(); i++) {
            View view = LayoutInflater.from(getActivity()).inflate(
                    R.layout.textview, null);
            TextView textView = (TextView) view.findViewById(R.id.text);
            ImageView img_del = (ImageView) view.findViewById(R.id.img_del);
            img_del.setVisibility(View.GONE);
            textView.setText(biaoqianlist.get(i).getName());
            textView.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.biaoqianshape));
            textView.setTextColor(Color.parseColor("#8c8c8c"));
            android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
                    android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
                    android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
            lP.setMargins(8, 0, 8, 8);
            view.setTag(i);
            flowLayout.addView(view, lP);
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(getActivity(),
                            ActivityToBiaoQian.class);
                    intent.putExtra("biaoqian",
                            biaoqianlist.get(Integer.parseInt(v.getTag() + ""))
                                    .getName());
                    intent.putExtra("biaoqianID",
                            biaoqianlist.get(Integer.parseInt(v.getTag() + ""))
                                    .getId());
                    startActivity(intent);
                }
            });
        }
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            pageNo = 1;
            model.setUid(SPUtils.get(getActivity(), null, SpPublicParams.UID, "")
                    + "");
            model.setFid(fid);
            model.setPage_no(pageNo + "");
            model.setMaxReply("2");
            model.setFresh(zuixin);
            presenter.getInfo(model);
            tag = false;
        }
    };
    TextView nodata;

    @SuppressWarnings("unchecked")
    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);

        if (entity != null) {
            IntentFilter filter = new IntentFilter("update");
            getActivity().registerReceiver(receiver, filter);
            tag = true;
            if (entity.getEventType() == BiaoQianPresenter.queryBiaoQIan_success) {
                biaoqianlist
                        .addAll((ArrayList<BiaoQianModel>) entity.getData());
                setbiaoqianname();

            }

            if (entity.getEventType() == TieZiPresenter.TieziFenYeSuccess) {
                if (model.getPage_no().equals("1")) {
                    aLists.clear();
                } else {
//                    aLists.clear();
                }
                aLists.addAll(((TieZiBaoHanReply) entity.getData()).getList());
                if (aLists.size() > 0) {
                    nodata.setVisibility(View.GONE);
                } else {
                    nodata.setVisibility(View.VISIBLE);
                }
                adapter.notifyDataSetChanged();
                try {
                    closeProgressDialog();
                } catch (Exception e) {

                }
            } else if (entity.getEventType() == TieZiPresenter.TiezifenyeFail) {
                nodata.setVisibility(View.VISIBLE);
            }

            if (entity.getEventType() == TieZiPresenter.DianzanSuccess) {
                ByAlert.alert(entity.getData() + "");
                Iterator<GetAList> iterable = aLists.iterator();
                while (iterable.hasNext()) {
                    GetAList getAList = iterable.next();
                    if (getAList.getTid().equals(tid)) {
                        getAList.setIsLike("1");
                        int count = Integer.parseInt(getAList.getLikes());
                        count = count + 1;
                        getAList.setLikes(count + "");
                        break;
                    }
                }
                adapter.notifyDataSetChanged();

            } else if (entity.getEventType() == TieZiPresenter.DianzanyeFail) {
                ByAlert.alert(entity.getData() + "");
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {

        }
        ptr.refreshComplete();
    }


}
